const app = getApp();
const WxParse = require('../../wxParse/wxParse.js');
Page({

    data: {
        tabIdx: 0,
        course_id: 0,
        info: {  },
        chapter: []
    },
    onLoad: function (options) {
       
        if (app.util.isUndefined(options.course_id) || options.course_id == 0) {
            app.error('课程id未传递', function() {
                wx.navigateBack({
                    delta: 1
                })
            })

            return;
        }
        this.data.course_id = options.course_id
        this.getInfo();
    },
    //发起http请求 获取课程信息
    getInfo() {
        app.http.$ajax({
            url: 'v1.learn/getCourse',
            data: {
                course_id: this.data.course_id
            },
            loading: '正在加载课程...'
        }, {
            success:(res)=> {
                app.processImg(res.data.images_arr);
                WxParse.wxParse('introduce', 'html', res.data.content, this, 5);
                this.setData({
                    info: res.data
                })
            }
        });
    },
    buy() {
        let that = this;
        app.http.$ajax({
            url: 'v1.pay/pay',
            data: {
                id: this.data.course_id
            }
        }, {
            success:(res)=> {
              let payData = JSON.parse(res.data);
              wx.requestPayment({
                ...payData,
                'success': function (res) {
                  app.success('支付成功', function() {
                    //刷新当前页面
                    that.getInfo();
                  })
                },
                'fail': function (res) {
                  app.error('支付失败')
                }
              })
            },
            fail: (res)=> {

            }
        })
    },
    open(e) {
        let chapter_id = e.currentTarget.dataset.chapter_id;
        if (this.data.info.is_buy != 1) {
            return app.info('请先购买课程');
        }
        if (this.data.info.is_chat == 1) {
          wx.navigateTo({
            url: '/pages/series-play/series-play?chapter_id=' + chapter_id,
          });
        } else {
          wx.navigateTo({
              url: '/pages/lesson-play/lesson-play?chapter_id=' + chapter_id,
          });
        }
    },
    getChapter() {
        app.http.$ajax({
            url: 'v1.learn/getChapter',
            data: {
                id: this.data.course_id
            },
            loading: '加载章节...'
        }, {
            success: (res) => {
                this.setData({
                    chapter: app.processImg(res.data)
                })
            }
        })
    },
    handleTab(e) {
        let idx = e.currentTarget.dataset.idx;
        if (idx == 1 && this.data.chapter.length == 0) {
            this.getChapter();
        }
        this.setData({
            tabIdx: idx
        })
    }
})